<template>
	<!-- 付款页面 - 待付款跳转 -->
	<view class="pay_container">
		<!-- 支付倒计时 -->
		<view class="pay_count_down">
			<view class="pay_count_down_info">
				<view class="">等待付款</view>
				<view class="count_down_tip_text">请在 {{ count_down }} 完成支付</view>
			</view>
			<view class="pay_count_down_pic">
				<image class="pay_count_down_pic_img" src="../../static/pay/count_down.png" mode="widthFix"></image>
			</view>
		</view>
		<!-- 收货地址组件 -->
		<view class="address_component">
			<Address :noticeChoseAddress="noticeChoseAddress"></Address>	
		</view>
		<!-- 商品卡片组件 -->
		<view class="goods_card">
			<GoodsCard></GoodsCard>
		</view>
		<!-- 订单参数 -->
		<view class="order_params">
			<view class="should_price order_param_item">
				<view class="should_price_text">
					订单金额
				</view>
				<view class="should_price_value">
					￥{{ orderInfo.shouldPrice }}
				</view>
			</view>
			<view class="coupon order_param_item">
				<view class="coupon_text">
					支付优惠
				</view>
				<view class="coupon_value">
					- ￥0.00
				</view>
			</view>
			<view class="real_price order_param_item">
				<view class="real_price_text">
					实付金额
				</view>
				<view class="real_price_value">
					￥<span style="font-size: 15px;">{{ orderInfo.realPrice }}</span>
				</view>
			</view>
		</view>
		<!-- 下单时间，订单编号 -->
		<view class="order_time_id">
			<view class="order_time order_param_item" >
				<view class="order_time_text">
					下单时间
				</view>
				<view class="order_time_value">
					{{ orderInfo.createTime }}
				</view>
			</view>
			<view class="order_id order_param_item">
				<view class="order_id_text">
					订单编号
				</view>
				<view class="order_id_value">
					{{ orderInfo.orderId }}
				</view>
			</view>
		</view>
		<!-- 结算框 -->
		<view class="settle_box">
			<view class="cancel_btn" @click="cancelOrderHandle">
				取消订单
			</view>
			<view class="settle_btn">
				<view class="should_pay">
					应付金额: <span style="color: red;">
								￥<span style="font-size: 15px;">{{ orderInfo.realPrice }}</span>	
							</span>
				</view>
				<view class="settle_btn_box">
					<button class="settle_btn_B" type="default" @click="payHandle">立即支付</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { onLoad } from '@dcloudio/uni-app';
import { ref, onMounted } from 'vue';
import Address from '../../components/Address/Address.vue';
import GoodsCard from '../../components/GoodsCard/GoodsCard.vue';
import dayjs from "dayjs"

// 订单ID
let payOrderId = ref('');
// 订单信息
let orderInfo = ref({});
// 支付倒计时
let count_down = ref('00:00');
// 收货地址选择标识
let choseAddressFlag = ref();

onLoad((options) => {
	payOrderId.value = options.orderId;
});

onMounted(() => {
	getOrderInfo();
});

// 立即支付处理器
function payHandle(){
	// 获取本地存储中首次预支付参数
	let prePayParam = uni.getStorageSync("prePayParam");
	payActive(prePayParam);
}


// 调起微信支付，执行支付
function payActive(payParam){
	uni.requestPayment({
	    "nonceStr": payParam.wxNonceStr, // 随机字符串
	    "package": payParam.wxPackage,        // 预支付订单号
	    "signType":payParam.wxSignType,     // 签名类型
	    "timeStamp": payParam.wxTimeStamp,  // 时间戳
	    "paySign": payParam.wxPaySign, // 签名，这里用的 RSA 签名
	    success(res) {
			// 支付成功处，处理购物车商品，页面跳转
			console.log("支付成功!");
			// 后续处理逻辑和页面跳转
			successPayAfterHandle();
		},
	    fail(e) {
			// 失败回调
			console.log("支付失败");
			uni.showToast({
				icon:"none",
				title: '支付失败!'
			});
		}
	})
}

// 支付成功处理器
function successPayAfterHandle(){
	uni.showToast({
		title: '支付成功',
		icon: "none"
	});
	
	// 跳转到订单页面"待收货"状态栏
	setTimeout(()=>{
		uni.navigateTo({
			url: `/subPkg2/order/order?state=1` // 跳转后选择状态为"待付款"
		})
	}, 1000)
}

// 取消订单按钮
function cancelOrderHandle(){
	// 确定取消按钮
	uni.showModal({
		title: '提示',
		content: '确定删除该订单？',
		success: function (res) {
			if (res.confirm) {
				execCancelOrderHanlde()
			} else if (res.cancel) {
				console.log("不取消");
			}
		}
	});
}

async function execCancelOrderHanlde(){
	const res = await uni.$http.put(`/orderInfos/cancelOrder/${payOrderId.value}`);
	if(res.data.code == 1){
		uni.showToast({
			title: '订单删除成功',
			icon: "none"
		});
		
		setTimeout(()=>{
			uni.navigateTo({
				url: `/subPkg2/order/order?state=5` // 跳转后选择状态为"已取消"
			})
		}, 1000)
		return 1;
	}
	
	uni.showToast({
		title: '订单删除失败',
		icon: "none"
	});
}

// 获取待支付的订单信息
async function getOrderInfo() {
	const res = await uni.$http.get(`/orderInfos/getOrderInfoById/${payOrderId.value}`);
	
	orderInfo.value = res.data.data;
	
	// 格式化时间
	orderInfo.value["createTime"] = dayjs(orderInfo.value.createTime).format("YYYY-MM-DD HH:mm:ss");
	
	// console.log('待支付订单ID：', orderInfo.value);
	// 处理器倒计时
	countDownHandle(res.data.data.createTime);
}

function countDownHandle(orderTime) {
	const orderDate = new Date(orderTime);
	const endDate = new Date(orderDate.getTime() + 15 * 60 * 1000); // 下单后15分钟的时间

	const updateTime = () => {
		const now = new Date();
		const difference = Math.floor((endDate - now) / 1000); // 计算剩余时间差（秒）

		if (difference > 0) {
			const minutes = Math.floor(difference / 60);
			const seconds = difference % 60;
			count_down.value = `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
		} else {
			count_down.value = '00:00'; // 倒计时结束
			clearInterval(interval); // 清除定时器
		}
	};

	updateTime(); // 初始化显示

	const interval = setInterval(updateTime, 1000); // 每秒更新

	return count_down.value;
}

// 收货地址组件通知修改是否选择了收货地址
function noticeChoseAddress(isSelect){
	if(isSelect){
		choseAddressFlag.value = isSelect;
	}
}
</script>

<style lang="scss" scoped>
.pay_count_down {
	display: flex;
	justify-content: space-between;
	padding: 0px 15rpx;
	align-items: center;
	background: linear-gradient(to right, #ef6134, #da6d4a);
	color: white;
}

.pay_count_down_btn_B {
	background-color: #ffa041;
	color: white;
	height: 70rpx;
	font-size: 15px;
	display: flex;
	justify-content: center;
	align-items: center;
	padding: 0px 30rpx;
}

.pay_count_down_pic {
	width: 30%;
}

.pay_count_down_pic_img {
	width: 100%;
}

.count_down_tip_text {
	font-size: 14px;
	padding-top: 10rpx;
}

.goods_card{
	width: 96%;
	margin: 0 auto;
	margin-top: 15rpx;
}

.order_param_item{
	display: flex;
	justify-content: space-between;
	padding: 30rpx 30rpx;
	color: #4d4d4d;
}

.order_params{
	width: 96%;
	margin: 0 auto;
	margin-top: 20rpx;
	background-color: #fff;
	font-size: 13px;
}

.real_price_value{
	color: #ea6d1a;
}

.real_price_text{
	color: #ea6d1a;
	font-size: 15px;
}

.real_price{
	background-color: #f7f7f7;
}

.order_time_id{
	background-color: #fff;
	width: 96%;
	margin: 0 auto;
	margin-top: 20rpx;
	font-size: 13px;
}

.settle_box{
	background-color: #fff;
	position: fixed;
	bottom: 0px;
	height: 100rpx;
	width: 100vw;
	display: flex;
	justify-content: space-between;
	font-size: 13px;
	align-items: center;
	padding: 0px 15rpx;
	color: #4d4d4d;
}

.settle_btn{
	display: flex;
	align-items: center;
	padding-right: 35rpx;
}

.settle_btn_B{
	background-color: #ff7f17;
	color: white;
	font-size: 14px;
	border-radius: 15px;
}

.should_pay{
	padding-right: 30rpx;
}
</style>
